<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" href="../../logo.svg" />
    <title>基本列表</title>
  </head>
  <body>
    <div id="root">
      <h2>人员列表</h2>
      <div>
        <input type="text" v-model="keyword" />
      </div>
      <ul>
        <li v-for="p in filterPersons" :key="p.id">
          {{p.name}} - {{p.age}} -- {{p.gender}}
        </li>
      </ul>
    </div>

    <script src="../../vue.js"></script>
    <script>
      Vue.config.productionTip = false; // 阻止 vue 在启动时生成生产提示。

      new Vue({
        el: "#root",
        data: {
          persons: [
            { id: 1, name: "马冬梅", age: 12, gender: "女" },
            { id: 2, name: "周冬雨", age: 19, gender: "女" },
            { id: 3, name: "周杰伦", age: 20, gender: "男" },
            { id: 4, name: "温兆伦", age: 21, gender: "男" },
          ],
          keyword: "",
        },
        computed: {
          filterPersons() {
            if (!this.keyword) {
              return this.persons;
            }
            return this.persons.filter(
              (p) => p.name.indexOf(this.keyword) >= 0
            );
          },
        },
      });

      // // --- 用 watch 实现
      // new Vue({
      //   el: "#root",
      //   data: {
      //     persons: [
      //       { id: 1, name: "马冬梅", age: 12, gender: "女" },
      //       { id: 2, name: "周冬雨", age: 19, gender: "女" },
      //       { id: 3, name: "周杰伦", age: 20, gender: "男" },
      //       { id: 4, name: "温兆伦", age: 21, gender: "男" },
      //     ],
      //     keyword: "",
      //     filterPersons: [],
      //   },
      //   watch: {
      //     keyword: {
      //       immediate: true,
      //       handler(val) {
      //         if (!val) {
      //           this.filterPersons = [...this.persons];
      //           return;
      //         }
      //         this.filterPersons = this.persons.filter(
      //           (p) => p.name.indexOf(val) >= 0
      //         );
      //       },
      //     },
      //   },
      // });
    </script>
  </body>
</html>
